package admin_Data;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import Email.SendMail;

import com.sun.crypto.provider.RSACipher;
import com.sun.org.apache.bcel.internal.generic.Select;

public class InnerSend extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public InnerSend() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>Servlet�ڲ�ʹ��</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("这个Servlet并不是公开的，请不要直接访问。");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		String idNode=request.getParameter("id");
		int id=Integer.parseInt(idNode.substring(3));
		String sqls1="SELECT * FROM notice WHERE id="+id;
		ResultSet notice_rs=null;
		ServletContext application=getServletContext();
		int notice_id=-1;
		String username="";
		String caption="";
		String summary="";
		String detail="";
		String towho="";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con=DriverManager.getConnection(application.getAttribute("dburl").toString()+"", application.getAttribute("username").toString(), application.getAttribute("password").toString());
			Statement sm=con.createStatement();
			notice_rs=sm.executeQuery(sqls1);
			notice_rs.next();
			notice_id=notice_rs.getInt(1);
			username=notice_rs.getString(2);
			caption=notice_rs.getString(3);
			summary=notice_rs.getString(4);
			detail=notice_rs.getString(5);
			towho=notice_rs.getString(6);
			String sqls2="SELECT id,email,username FROM iemail";
			ResultSet email_rs=sm.executeQuery(sqls2);
			email_rs.last();
			int email_len=email_rs.getRow();
			email_rs.beforeFirst();
			JSONObject towho_jo=null;
			JSONArray towho_ja=null;
			if(towho!="" && towho!=null){
				towho_jo=JSONObject.fromObject(towho);
				towho_ja=towho_jo.getJSONArray("user");
				int towho_len=towho_ja.size();
				for(int i=0;i<towho_len;++i){
					String t_to_who=towho_ja.getJSONObject(i).getString("name");
					for(int j=0;j<email_len;++j){
						email_rs.next();
						int tsendid=email_rs.getInt(1);
						String tmail=email_rs.getString(2);
						String tusername=email_rs.getString(3);
						if(tusername.equals(t_to_who)==true){
							SendEmail(caption, tusername, tusername, summary, detail, tmail, String.valueOf(tsendid));
						}
					}
					email_rs.beforeFirst();
				}
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print("succes");
		out.flush();
		out.close();
	}
	
	private void SendEmail(String caption,String username,String inner_username,String summary,String detail,String sendto,String sendid) throws Exception{
		ServletContext application=getServletContext();
		String thishost=(String) application.getAttribute("thishost");
		String privatehost=(String) application.getAttribute("privatehost");
		String smtphost=(String) application.getAttribute("smtphost");
		String smtpusername=(String) application.getAttribute("smtpusername");
		String smtppassword=(String) application.getAttribute("smtppassword");
		String content="<center><h1><font color=\"red\">Jstudio-NoticeSystem公告信息</font></h1>"
				+ "<table>"
				+ "<tr>"
				+ "<td>公告类别：</td>"
				+ "<td>内部公告</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>标题：</td>"
				+ "<td>"+caption+"</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>发布者：</td>"
				+ "<td>"+username+"</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>获得此公告的内部访问用户：</td>"
				+ "<td>"+inner_username+"</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>简介：</td>"
				+ "<td>"+summary+"</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>详细内容：</td>"
				+ "<td>"+detail+"</td>"
				+ "</tr>"
				+ "<tr>"
				+ "<td>相关操作：</td>"
				+ "<td>"
				+ "<a href=\""+thishost+"inner-notice.jsp\">访问内部公告（外网访问）</a><br/>"
				+ "<a href=\""+privatehost+"inner-notice.jsp\">访问内部公告（内网访问）</a><br/>"
				+ "<a href=\""+thishost+"inner/unsubscribe.jsp?id="+sendid+"\">退订邮件推送（外网访问）</a><br/>"
				+ "<a href=\""+privatehost+"inner/unsubscribe.jsp?id="+sendid+"\">退订邮件推送（内网访问）</a><br/>"
				+ "</td>"
				+ "</tr>"
				+ "</table>"
				+ "</center>";
		System.out.println(content);
		SendMail.send(smtphost, smtpusername, smtppassword, smtpusername, sendto, "NoticeSystem推送："+caption, content);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
